<!-- src/views/PostDetailView.vue -->
<template>
  <div class="post-detail-container" v-loading="loading">
    <el-page-header @back="$router.go(-1)" :content="post.title || '加载中...'" style="margin-bottom: 20px;" />

    <div v-if="post.id" class="post-content">
      <h1>{{ post.title }}</h1>
      <div class="post-meta">
       <!-- *** 修改点: 更新作者链接 *** -->
        <span>作者: <el-link type="primary" @click="goToUser(post.authorId)">{{ post.authorName }}</el-link></span> |
        <span>板块: {{ post.categoryName }}</span> |
        <span>发布时间: {{ formatDate(post.createdAt) }}</span> |
        <span>浏览: {{ post.viewCount }}</span> |
        <span>评论: {{ post.replyCount }}</span> |
        <span>点赞: {{ post.likeCount }}</span>
        <el-tag v-if="post.isTop" type="danger" size="small" effect="dark" style="margin-left: 8px;">置顶</el-tag>
        <el-tag v-if="post.isEssence" type="warning" size="small" effect="light" style="margin-left: 4px;">精华</el-tag>
      </div>
      <div class="post-body" v-html="sanitizeHtml(post.content)"></div> <!-- 注意 XSS 风险 -->

      <!-- 互动按钮 -->
      <div class="post-actions">
        <el-button type="primary" @click="toggleLike" :loading="likeLoading" size="small">
          {{ isLiked ? '取消点赞' : '点赞' }} ({{ post.likeCount }})
        </el-button>
        <el-button type="warning" @click="toggleFavorite" :loading="favLoading" size="small">
          {{ isFavorited ? '取消收藏' : '收藏' }} ({{ post.favoriteCount }})
        </el-button>
        <!-- 可以添加编辑、删除按钮，根据权限显示 -->
         <!-- *** 新增: 编辑和删除按钮 *** -->
        <template v-if="authStore.isAuthenticated">
          <el-button
            v-if="canEditPost"
            type="success"
            size="small"
            @click="$router.push(`/posts/${post.id}/edit`)"
          >
            编辑
          </el-button>
          <el-button
            v-if="canDeletePost"
            type="danger"
            size="small"
            @click="confirmDeletePost"
          >
            删除
          </el-button>
        </template>
      </div>
    </div>

    <div v-if="post.id" class="replies-section">
      <h2>评论 ({{ post.replyCount }})</h2>
      <!-- 发表回复表单 (顶级回复) -->
      <ReplyForm
        v-if="authStore.isAuthenticated"
        :post-id="Number(postId)"
        :show-cancel="false"
         @reply-submitted="onNewReplySubmitted"
      />
      <div v-else class="login-prompt">
        <p>请 <el-link type="primary" @click="$router.push('/login')">登录</el-link> 后发表评论。</p>
      </div>

      <!-- 回复列表 (简化版，实际需要递归组件处理嵌套) -->
      <div v-for="reply in replies" :key="reply.id" class="reply-item">
        <div class="reply-header">
          <strong>{{ reply.authorName }}</strong>
          <span class="reply-time">{{ formatDate(reply.createdAt) }}</span>
        </div>
        <div class="reply-content">{{ reply.content }}</div>
        <div class="reply-actions">
           <!-- <el-button size="small" @click="handleLikeReply(reply)" :loading="reply.likeLoading">点赞 ({{ reply.likeCount }})</el-button> -->
          <!-- 可以添加回复按钮，触发显示 ReplyForm -->
          <!-- <el-button size="small" @click="showReplyForm(reply.id)">回复</el-button> -->
            <el-button size="small" @click="handleLikeReply(reply)" :loading="reply.likeLoading">点赞 ({{ reply.likeCount }})</el-button>
            <!-- *** 新增: 回复编辑和删除按钮 *** -->
          <template v-if="authStore.isAuthenticated">
            <el-button
              v-if="canEditReply(reply)"
              size="small"
              @click="startEditingReply(reply)"
            >
              编辑
            </el-button>
            <el-button
              v-if="canDeleteReply(reply)"
              size="small"
              type="danger"
              @click="confirmDeleteReply(reply)"
            >
              删除
            </el-button>
          </template>
          <!-- *** *** -->
        </div>

        <!-- *** 新增: 编辑回复表单 (内联) *** -->
        <div v-if="reply.isEditing" class="reply-edit-form">
          <el-input
            v-model="reply.editContent"
            type="textarea"
            :rows="3"
            placeholder="编辑回复内容..."
          ></el-input>
          <div style="margin-top: 10px;">
            <el-button type="primary" size="small" @click="saveEditedReply(reply)" :loading="reply.saving">保存</el-button>
            <el-button size="small" @click="cancelEditingReply(reply)">取消</el-button>
          </div>
        </div>
        <!-- *** *** -->
      </div>

      <!-- ... (existing pagination) ... -->
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'; // 引入 watch
import { ElMessageBox,ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { getPostById, likePost, unlikePost, favoritePost, unfavoritePost } from '@/services/postService';
import { getRepliesByPostId, createReply, likeReply, unlikeReply , deleteReply, updateReply} from '@/services/replyService'; // 引入回复服务
import ReplyForm from '@/components/ReplyForm.vue';
import dayjs from 'dayjs';
import DOMPurify from 'dompurify';
import { deletePost,updatePost } from '@/services/postService'; // 引入删除服务

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();

const loading = ref(false);
const likeLoading = ref(false);
const favLoading = ref(false);

const post = ref({
  id: null, title: '', content: '', authorId: null, authorName: '',
  categoryName: '', viewCount: 0, replyCount: 0, likeCount: 0,
  favoriteCount: 0, isTop: 0, isEssence: 0, createdAt: '', updatedAt: ''
});



const replies = ref([]); // 存储回复列表
// const flatReplies = computed(() => replies.value.flat()); // 如果 replies 是嵌套的，需要展平 (暂时不需要)

const postId = computed(() => route.params.id);

// --- 新增：分页和加载状态 ---
const replyPagination = reactive({
  page: 0, // 后端从0开始
  size: 10,
  total: 0,
  loading: false
});
// --- ---

const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
};

const sanitizeHtml = (htmlContent) => {
  return DOMPurify.sanitize(htmlContent || '');
};

// 获取帖子详情和回复
// --- 更新：获取帖子详情 ---
const fetchPostDetail = async () => {
  if (!postId.value) return;
  loading.value = true;
  try {
    const response = await getPostById(postId.value);
    post.value = response.data;
    // 获取回复列表也放在这里，或者单独调用 fetchReplies
    await fetchReplies(); // 获取第一页回复
  } catch (error) {
    console.error('Failed to fetch post detail:', error);
    ElMessage.error(error.response?.data?.message || '获取帖子详情失败');
    if (error.response?.status === 404) {
      router.push('/404');
    }
  } finally {
    loading.value = false;
  }
};

// --- 新增：获取回复列表 (分页) ---
const fetchReplies = async (page = 0) => {
    if (!postId.value) return;
    replyPagination.loading = true;
    replyPagination.page = page; // 更新当前页
    try {
        const response = await getRepliesByPostId(postId.value, {
            page: page,
            size: replyPagination.size
            // 可以添加排序参数
        });
        // 假设后端返回的是分页数据 { content: [...], totalElements: ... }
        replies.value = response.data.content || [];
        replyPagination.total = response.data.totalElements || response.data.total || 0;
        // 为每个回复添加本地加载状态 (用于点赞)
        replies.value.forEach(r =>{
             r.likeLoading = false;
             // *** 新增: 初始化编辑相关状态 ***
             r.isEditing = false;
             r.editContent = '';
             r.saving = false;
             // *** ***
        });
    } catch (error) {
        console.error('Failed to fetch replies:', error);
        ElMessage.error('获取回复列表失败');
    } finally {
        replyPagination.loading = false;
    }
};

// --- 新增: 跳转到用户详情页 ---
const goToUser = (userId) => {
  if (userId) {
    router.push(`/users/${userId}`);
  }
};

// --- 新增：处理分页变化 ---
const handleReplyPageChange = (newPage) => {
    fetchReplies(newPage - 1); // Element UI 页码从1开始，后端从0开始
};

// --- 更新：处理回复点赞 ---
const handleLikeReply = async (reply) => {
  if (!authStore.isAuthenticated) {
    router.push('/login');
    return;
  }
  // 设置该回复的本地加载状态
  reply.likeLoading = true;
  try {
    // 检查当前用户是否已点赞 (需要后端支持或前端状态判断)
    // 这里简化处理，假设前端没有状态，调用 API 后根据结果判断
    // 更好的方式是在回复数据中包含 isLikedByCurrentUser 字段
    if (reply.isLikedByCurrentUser) { // 假设有这个字段
         await unlikeReply(reply.id);
         reply.likeCount -= 1;
         reply.isLikedByCurrentUser = false;
         ElMessage.success('取消点赞成功');
    } else {
         await likeReply(reply.id);
         reply.likeCount += 1;
         reply.isLikedByCurrentUser = true;
         ElMessage.success('点赞成功');
    }
    // 或者总是调用，让后端处理重复/取消逻辑，前端只更新计数
    // await likeReply(reply.id);
    // reply.likeCount += 1; // 假设总是成功增加
    // ElMessage.success('点赞成功');

  } catch (error) {
    console.error('Like reply failed:', error);
    ElMessage.error(error.response?.data?.message || '点赞失败');
  } finally {
    reply.likeLoading = false;
  }
};

// --- 更新：处理提交新回复 ---
const onNewReplySubmitted = async (newReply) => {
  console.log('New reply submitted (from API):', newReply);
  // 1. 将新回复添加到列表 (可以选择添加到顶部或底部)
  //    为了实时性，通常添加到顶部
  //    但要考虑分页，如果在第一页且未满，可以添加；否则最好重新加载第一页
  //    简化处理：添加到顶部
  if (replyPagination.page === 0 && replies.value.length < replyPagination.size) {
       replies.value.unshift(newReply);
  } else {
       // 如果不在第一页或当前页已满，重新加载第一页
       await fetchReplies(0);
  }
  // 2. 更新帖子的回复计数
  post.value.replyCount += 1;
  ElMessage.success('评论发表成功');
  // 3. 可以滚动到新回复位置或给出提示
};


// 点赞/取消点赞帖子
const toggleLike = async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login');
    return;
  }
  likeLoading.value = true;
  try {
    if (post.value.isLikedByCurrentUser) { // 假设后端或前端计算了这个状态
      await unlikePost(postId.value);
      post.value.likeCount -= 1;
      post.value.isLikedByCurrentUser = false;
    } else {
      await likePost(postId.value);
      post.value.likeCount += 1;
      post.value.isLikedByCurrentUser = true;
    }
  } catch (error) {
    console.error('Like/Unlike post failed:', error);
    ElMessage.error(error.response?.data?.message || '操作失败');
  } finally {
    likeLoading.value = false;
  }
};

// 收藏/取消收藏帖子
const toggleFavorite = async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login');
    return;
  }
  favLoading.value = true;
  try {
    if (post.value.isFavoritedByCurrentUser) { // 假设后端或前端计算了这个状态
      await unfavoritePost(postId.value);
      post.value.favoriteCount -= 1;
      post.value.isFavoritedByCurrentUser = false;
    } else {
      await favoritePost(postId.value);
      post.value.favoriteCount += 1;
      post.value.isFavoritedByCurrentUser = true;
    }
  } catch (error) {
    console.error('Favorite/Unfavorite post failed:', error);
    ElMessage.error(error.response?.data?.message || '操作失败');
  } finally {
    favLoading.value = false;
  }
};



// 提交顶级回复
const onReplySubmitted = (newReply) => {
  console.log('New top-level reply submitted:', newReply);
  // 将新回复添加到列表顶部或重新获取列表
  replies.value.unshift(newReply); // 添加到顶部
  post.value.replyCount += 1; // 更新帖子回复数
};

const canEditPost = computed(() => {
  return authStore.isAuthenticated &&
         (authStore.currentUser?.id === post.value.authorId ||
          authStore.currentUser?.roles?.includes('MANAGE') ||
          authStore.currentUser?.roles?.includes('OWN')); // 假设版主/管理员也能编辑
});

const canDeletePost = computed(() => {
  return authStore.isAuthenticated &&
         (authStore.currentUser?.id === post.value.authorId ||
          authStore.currentUser?.roles?.includes('OWN') ||
          authStore.currentUser?.roles?.includes('MANAGE'));
});

const canEditReply = (reply) => {
  return authStore.isAuthenticated &&
         (authStore.currentUser?.id === reply.authorId ||
          authStore.currentUser?.roles?.includes('OWN') ||
          authStore.currentUser?.roles?.includes('MANAGE'));
};

const canDeleteReply = (reply) => {
  return authStore.isAuthenticated &&
         (authStore.currentUser?.id === reply.authorId ||
          authStore.currentUser?.roles?.includes('OWN') ||
          authStore.currentUser?.roles?.includes('MANAGE'));
};

const confirmDeletePost = () => {
  ElMessageBox.confirm(
    '确定要删除这篇帖子吗？此操作不可撤销。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deletePost(postId.value);
      ElMessage.success('帖子删除成功');
      // 删除成功后，跳转到帖子列表页或其他页面
      router.push('/posts');
    } catch (error) {
      console.error('Post deletion failed:', error);
      ElMessage.error(error.response?.data?.message || '删除失败');
    }
  }).catch(() => {
    // 用户取消删除
  });
};
// --- ---

// --- Methods for Reply Actions ---
const startEditingReply = (reply) => {
  reply.isEditing = true;
  // 初始化编辑内容为原始内容
  reply.editContent = reply.content;
  reply.saving = false; // 初始化保存状态
};

const cancelEditingReply = (reply) => {
  reply.isEditing = false;
  // reply.editContent = ''; // 可以清空，也可以保留
  reply.saving = false;
};

const saveEditedReply = async (reply) => {
  if (!reply.editContent?.trim()) {
    ElMessage.warning('回复内容不能为空');
    return;
  }
  reply.saving = true;
  try {
    const response = await updateReply(reply.id, { content: reply.editContent });
    console.log('Reply updated:', response.data);
    // 更新本地列表中的回复内容
    reply.content = response.data.content; // 使用后端返回的更新后内容（可能包含格式化）
    reply.updatedAt = response.data.updatedAt; // 更新时间
    reply.isEditing = false;
    ElMessage.success('回复更新成功');
  } catch (error) {
    console.error('Reply update failed:', error);
    ElMessage.error(error.response?.data?.message || '更新失败');
  } finally {
    reply.saving = false;
  }
};

const confirmDeleteReply = (reply) => {
  ElMessageBox.confirm(
    '确定要删除这条回复吗？此操作不可撤销。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteReply(reply.id);
      console.log('Reply deleted:', reply.id);
      // 从本地列表中移除回复
      const index = replies.value.findIndex(r => r.id === reply.id);
      if (index > -1) {
        replies.value.splice(index, 1);
        // 更新帖子回复数
        post.value.replyCount = Math.max(0, post.value.replyCount - 1);
      }
      ElMessage.success('回复删除成功');
    } catch (error) {
      console.error('Reply deletion failed:', error);
      ElMessage.error(error.response?.data?.message || '删除失败');
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 组件挂载时获取数据
onMounted(() => {
  fetchPostDetail();
});

// 监听路由参数变化 (如果从一个帖子详情页导航到另一个)
// import { watch } from 'vue';
// watch(postId, (newId, oldId) => {
//   if (newId !== oldId) {
//     fetchPostDetail();
//   }
// });
</script>

<style scoped>
.post-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}
.post-meta {
  margin-bottom: 20px;
  color: #999;
  font-size: 0.9em;
}

/* *** 新增: 编辑回复表单样式 *** */
.reply-edit-form {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
}
.post-body {
  white-space: pre-wrap; /* 保留换行和空格 */
  text-align: left;
  border-top: 1px solid #eee;
  padding-top: 20px;
  margin-top: 20px;
}
.post-actions {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}
.replies-section {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}
.reply-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}
.reply-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.reply-time {
  color: #999;
  font-size: 0.85em;
}
.reply-content {
  margin-bottom: 10px;
  text-align: left;
}
.reply-actions {
  text-align: right;
}
.login-prompt {
  margin-top: 20px;
  text-align: center;
  color: #666;
}
</style>
